﻿<%@ WebHandler Language="C#" Class="Automations" %>

using System;
using System.Web;
using System.Xml;
using System.Xml.XPath;
using System.Collections.Generic;
using System.Text;

public class Automations : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/html";
        string fileName = HttpContext.Current.Server.MapPath(Constant.XmlFileName);
        context.Response.Write(
            ToJsonString(LoadApplications(fileName))
            );
    }

    private Dictionary<string, string> LoadApplications(string fileName)
    {
        Dictionary<string, string> applications = new Dictionary<string, string>();

        XPathDocument xmlDoc = new XPathDocument(fileName);
        string automationPath = "//Automation[@id]";
        var nav = xmlDoc.CreateNavigator();
        var automationNav = nav.Select(automationPath);
        while (automationNav.MoveNext())
        {
            string appId = automationNav.Current.GetAttribute("id", "");
            string appName = string.Empty;
            if (automationNav.Current.MoveToChild("Name", ""))
            {
                appName = automationNav.Current.Value;
                applications.Add(appId, appName);
            }
        }
        return applications;
    }

    private string ToJsonString(Dictionary<string, string> applications)
    {
        var jsonBuilder = new StringBuilder(@"[");
        foreach (string appId in applications.Keys)
        {
            jsonBuilder.Append("{");
            jsonBuilder.AppendFormat(@"'text':'{0}','id':'{1}','leaf':true ,'cls':'file'", applications[appId], appId);
            jsonBuilder.Append("},");
        }
        jsonBuilder = jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append(@"]");
        return jsonBuilder.ToString();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}